package com.rocksea.app.http;

import android.os.AsyncTask;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.LinkedHashMap;

/**
 * Created by Mrw on 2017/8/5.
 *
 */

public class CommHttpTask extends AsyncTask<Void,Void,String>{
    public static final String GET_PUBLIC_KEYPublicKey = "getPublicKey";
    public static final String VERIFY_APP_USER = "verifyAppUser";
    public static final String DOWN_SECT = "downSect";
    public static final String DOWN_INSPECTION_FROM_1 = "downInspectionFormRoad";
    public static final String DOWN_INSPECTION_FROM = "downInspectionForm";
    public static final String DOWN_SITE = "downSiteBySectId";
    private String methodName;
    private OnRespond mOnRespond;
    private LinkedHashMap<String,Object> mPropertys;
    public CommHttpTask(String methodName, LinkedHashMap<String,Object> mPropertys, OnRespond mOnRespond) {
        this.methodName = methodName;
        this.mOnRespond = mOnRespond;
        this.mPropertys = mPropertys;
    }
    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }
    @Override
    protected String doInBackground(Void... params) {
        String serviceNameSpace=Config.ServiceNameSpace;
        String serviceURL=Config.ServiceUrl;
        SoapObject request = new SoapObject(serviceNameSpace,methodName);
        for (LinkedHashMap.Entry<String, Object> entry : mPropertys.entrySet())
        {
            request.addProperty(entry.getKey(),entry.getValue());
        }
        SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut=request;
        (new MarshalBase64()).register(envelope);
        //Android传输对象
        HttpTransportSE transport=new HttpTransportSE(serviceURL);
        try {
            transport.call(serviceNameSpace+methodName,envelope);
            if(envelope.getResponse()!=null){
                SoapObject object = (SoapObject) envelope.bodyIn;
                return object.getProperty(0).toString();
            }
            else {
                return null;
            }
        } catch (IOException | XmlPullParserException e) {
            e.printStackTrace();
            return null;
        }
    }
    @Override
    protected void onPostExecute(String s)
    {
        super.onPostExecute(s);
        if (s!=null)
            mOnRespond.onSucceed(s);
        else
            mOnRespond.onError(Config.ERROR_NET,"获取数据失败");
    }
}
